package com.boby.homecamera.activity.client

import android.Manifest
import android.app.Activity
import android.app.ActivityOptions
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.Gravity
import android.view.View
import android.view.WindowInsetsController
import android.widget.LinearLayout
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.boby.homecamera.R
import com.boby.homecamera.activity.LauncherActivity
import com.boby.homecamera.activity.server.InitServerActivity
import com.boby.homecamera.adapter.CameraDeviceAdapter
import com.boby.homecamera.config.AppConfig
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.db.CameraDeviceTable
import com.boby.homecamera.db.CameraDeviceTable.CameraDevice
import com.boby.homecamera.db.ClientDBManager
import com.boby.homecamera.service.ClientMsgService
import com.boby.homecamera.service.MainService
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.extens.getParcelableExtraData
import com.boby.lib_common.extens.setVisible
import com.boby.lib_common.extens.toast
import com.boby.lib_common.util.BLog
import com.lxj.xpopup.XPopup

class ClientHomeActivity : BaseActivity() {
    private val TAG = "ClientHomeActivity"
    private lateinit var tv_empty_tip:View
    private lateinit var rv_camera_list: RecyclerView
    private val cameraDeviceList = mutableListOf<CameraDeviceTable.CameraDevice>()
    private var cameraDeviceAdapter = CameraDeviceAdapter(cameraDeviceList)

    private val permissions: Array<String>

    init {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissions = arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.FOREGROUND_SERVICE,
                Manifest.permission.FOREGROUND_SERVICE_MICROPHONE,
                Manifest.permission.POST_NOTIFICATIONS
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            permissions = arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.FOREGROUND_SERVICE
            )
        } else {
            permissions = arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_client_home)
        val toolbar: Toolbar = findViewById(R.id.mToolbar)
        setSupportActionBar(toolbar)
        initToolBar(toolbar)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                window.insetsController?.setSystemBarsAppearance(
                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
                )
            }else{
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                            View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
            }
        }else{
            // 设置状态栏白底
            window.statusBarColor = Color.WHITE
            // 设置状态栏字体图标为黑色（亮色模式 = false）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }
        initView()
        if(hasPermissions(this, *permissions)){
            startServer()
        }else{
            ActivityCompat.requestPermissions(this, permissions, 1996)
        }


    }

    private fun initView(){
        tv_empty_tip = findViewById(R.id.tv_empty_tip)
        rv_camera_list = findViewById(R.id.rv_camera_list)

        val iv_menu =  findViewById<View>(R.id.iv_menu)
        iv_menu.setOnClickListener {
            val popup = PopupMenu(this, it)
            popup.menuInflater.inflate(R.menu.client_home_menu, popup.menu)
            popup.setOnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.menu_add -> {
                        CameraEditActivity.start(this,0,launcher)
                        true
                    }
                    R.id.menu_exit -> {
                        AppConfig.deviceModel = Constant.DEVICE_MODEL_UNSELECT
                        val option = ActivityOptions.makeCustomAnimation(this, com.boby.lib_common.R.anim.slide_in_left, com.boby.lib_common.R.anim.slide_out_right)
                        startActivity(Intent(this, LauncherActivity::class.java),option.toBundle())
                        finish()
                        true
                    }
                    else -> false
                }
            }

            popup.show()
        }

        rv_camera_list.adapter = cameraDeviceAdapter
        rv_camera_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL,false)
        cameraDeviceAdapter.setItemClickListener {
            CameraClientActivity.start(this,it)
        }

        cameraDeviceAdapter.setOperationClickListener {view,index,item ->
            XPopup.Builder(this)
                .atView(view)
                .asAttachList(arrayOf("编辑","删除"),null,{ position,st ->
                    if(position == 0){
                        CameraEditActivity.start(this,1,launcher,item)
                    }else if (position == 1){
                        ClientDBManager.instance.tb_camrea_device.delete(item.id)
                        cameraDeviceList.removeAt(position)
                        cameraDeviceAdapter.notifyItemRemoved(index)
                    }
                })
                .show()
        }
    }
    private fun initData(){
        var list = ClientDBManager.instance.tb_camrea_device.queryAll()
        BLog.d(TAG,"$list")
        cameraDeviceList.clear()
        cameraDeviceList.addAll(list)
        cameraDeviceAdapter.notifyDataSetChanged()
        if(cameraDeviceList.isEmpty()){
            rv_camera_list.setVisible(false)
            tv_empty_tip.setVisible(true)
        }else{
            rv_camera_list.setVisible(true)
            tv_empty_tip.setVisible(false)
        }
    }

    fun addCameraDevice(view: View) {
        CameraEditActivity.start(this,0,launcher)
    }

    private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data = result.data
            val type = data!!.getIntExtra("type",0)
            val cameraData = data.getParcelableExtraData<CameraDevice>("data", CameraDevice::class.java)
            if(cameraData == null){
                return@registerForActivityResult
            }
            if(type == 0){
               //新增
                var addIndex = cameraDeviceList.size
                cameraDeviceList.add(cameraData)
                cameraDeviceAdapter.notifyItemInserted(addIndex)
                rv_camera_list.setVisible(true)
                tv_empty_tip.setVisible(false)
            }else{
                var updateIndex = -1
                cameraDeviceList.forEachIndexed { index,cameraDevice ->
                    if(cameraDevice.id == cameraData.id){
                        updateIndex = index
                        return@forEachIndexed
                    }
                }
                if(updateIndex != -1){
                    cameraDeviceList[updateIndex] = cameraData
                    cameraDeviceAdapter.notifyItemChanged(updateIndex)
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String?>,
        grantResults: IntArray,
        deviceId: Int
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults, deviceId)
        if(requestCode == 1996){
            if(grantResults.isNotEmpty()){
                for (result in grantResults){
                    if(result != PackageManager.PERMISSION_GRANTED){
                        toast("请授予必要的权限")
                        ActivityCompat.requestPermissions(this, this@ClientHomeActivity.permissions, 1996)
                        return
                    }
                }
                startServer()
            }
        }
    }

    private fun hasPermissions(context: Context?, vararg permissions: String): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null) {
            for (permission in permissions) {
                if (ActivityCompat.checkSelfPermission(
                        context,
                        permission
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return false
                }
            }
        }
        return true
    }

    private fun startServer() {
        val intent = Intent(this, ClientMsgService::class.java)
        startService(intent)
        bindService(intent, serviceConnection, BIND_AUTO_CREATE)
    }
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            BLog.d(TAG,"onServiceConnected")

            initData()
        }

        override fun onServiceDisconnected(name: ComponentName?) {

        }
    }

}